% a statewait task for the eyelink with no error feedback
clear;
close all;
cd C:\_bcoe\Eyelink2_Data\;

c=clock;
day=[num2str(c(1)) '_' num2str(c(2)) '_' num2str(c(3)) ];
if day(7)=='_'
    day=[day(1:5), '0',day(6:end)];
end
if length(day)==9;
    day=[day(1:8), '0',day(9:end)];
end

eval(['mkdir ' day]);
eval(['cd ' day]);
c=define_colors;
c.BACKGROUND=c.M_GREY;
c.PRO=c.BLUE;
c.ANTI=c.ORANGE;

% Number of Delays between fix offset and cue-target onset
delay=[0 .5 1 ]; %in secs
n_dly=length(delay);

% Number of Locations
% 135  90  45
% 180  +  360
% 225 270 315
% angle of 0 means ecc of 0 and vice versa!
loc_AngEcc=	[ 45 12; 135 12; 225 12; 315 12];    % ang & ecc positions. only change this line!!!
n_loc=length(loc_AngEcc);
loc_XY=[]; 
[loc_XY(:,1) loc_XY(:,2)]=polar2cart(loc_AngEcc(:,1),loc_AngEcc(:,2),1);   
[loc_XYm(:,1) loc_XYm(:,2)]=polar2cart(loc_AngEcc(:,1),loc_AngEcc(:,2)+.6,1);  % the +.6 is for the width of the targtes which may have to be changed 
%loc_XY(:,2)=-loc_XY(:,2);  reverse vertical for robarts eyeview
[w,screenRect] = SCREEN(0,'OpenWindow',0,[],16);
SCREEN(w,'Close');
c_x=screenRect(3)/2;
c_y=screenRect(4)/2;
% for now....
clc;
dist2screen=60;
screenwidth=36;
if dist2screen*screenwidth
	[ang ecc]=cart2polar(dist2screen,screenwidth/2);
else
	ang=30;
end	
pixperdeg=screenRect(3)/(ang*2);
s_circle=[-1 -1	1 1]*pixperdeg*.4; 								% stimulus circle
fix_b=round([c_x c_y c_x c_y]+([-1 -1	1 1]*pixperdeg*.09));	% fixation middle
fix_a=round([c_x c_y c_x c_y]+([-1 -1	1 1]*pixperdeg*.4));	% fixation circle

pixloc_XY=[];
pixloc_XY(:,1)=(loc_XYm(:,1)*pixperdeg)+c_x;% set ang&ecc to x&y based on screen size
pixloc_XY(:,2)=(loc_XYm(:,2)*pixperdeg)+c_y;
for i=1:n_loc
	marker_rect(i,:)=round([pixloc_XY(i,:) pixloc_XY(i,:)]+[-2 -2 2 2]); % for use with mac's LeToRiBo rect shite
end
pixloc_XY=[];
pixloc_XY(:,1)=(loc_XY(:,1)*pixperdeg)+c_x;% set ang&ecc to x&y based on screen size
pixloc_XY(:,2)=(loc_XY(:,2)*pixperdeg)+c_y;
for i=1:n_loc
	tgt_rect(i,:)=round([pixloc_XY(i,:) pixloc_XY(i,:)]+s_circle); % for use with mac's LeToRiBo rect shite
end

test=[];
index=0;
for i=1:n_loc	% number of locations
	for j=1:2	%  pro v anti
		for k=1	% cent v peri 1 or 2
			for l=1:n_dly	% number of delays
				index=index+1;
				test(index,:)=[i j k l];   
			end
		end
	end
end

temp=test;
for i=2:1 % number of repetitions
    temp=[temp; test];
end
test=temp;

final=[];
for i=1:length(test)
    index=ceil(rand*size(test,1));
    final(i,:)=test(index,:);
    test(index,:)=[];
end
% fuzzy booleans
w_loc=final(:,1);
% w_anti=final(:,2)-1;
% w_peri=final(:,3)-1;
% w_delay=final(:,4);
max_trials=length(final);

clear('test', 'temp', 'index','i');
A=[];
A.clock=round(clock);
A.ang_ecc=loc_AngEcc(final(:,1),:);
A.anti=final(:,2)-1;
A.peri=final(:,3)-1;
A.delay=delay(final(:,4))';

clear t_state
% set trial states and their relative timing in secs
S_ITI     =1; dur_iti=10; t_state(S_ITI     ,:)=' ITI      ';  % duration of iti
S_FIX     =2; dur_fix=2;  t_state(S_FIX     ,:)=' FIX      ';  % duration of fix WITHOUT checking eye
S_GAP     =3;             t_state(S_GAP     ,:)=' GAP      ';  % random duration
S_CUE_TGT =4; dur_c_t=.1; t_state(S_CUE_TGT ,:)=' CUE_TGT  ';  % duration of cue&tgt WITHOUT checking eye
S_BLACK   =5; dur_blk=4;  t_state(S_BLACK   ,:)=' BLACK    '; 
max_dur=max([dur_iti dur_fix dur_c_t dur_blk])
A.t_state=t_state;
A.pixperdeg=pixperdeg;
A.screenRect=screenRect;
A.colors=c;

state_event=S_ITI; % S_ITI
state_duration=dur_iti; % S_ITI
for tr_num = 1:max_trials
    state_event(end+1)=S_FIX;
    state_duration(end+1)=dur_fix;
    
    state_event(end+1)=S_GAP;
    state_duration(end+1)=A.delay(tr_num);;
    
    state_event(end+1)=S_CUE_TGT;
    state_duration(end+1)=dur_c_t;
    
    state_event(end+1)=S_BLACK;
    state_duration(end+1)=dur_blk-dur_c_t-A.delay(tr_num);
    
	state_event(end+1)=S_ITI;
	state_duration(end+1)=dur_iti;
end
state_duration=state_duration';
state_event=state_event';
state_end_time=cumsum([ state_duration]);
if min(diff(state_end_time))<0                  % sort is not really necessary unless you include S_OVERLAP 
    [state_end_time temp]=sort(state_end_time); % sort is not really necessary unless you include S_OVERLAP 
    state_event= state_event(temp)';            % sort is not really necessary unless you include S_OVERLAP 
    state_duration= state_duration(temp)';      % sort is not really necessary unless you include S_OVERLAP 
    clear temp;
end
if min(diff(state_end_time))==0                  % clearing is not really necessary unless you include a 0 ms delay (i.e. strep task which skips the isi gap) 
    state_event(state_duration==0)=[];
    state_end_time(state_duration==0)=[];
    state_duration(state_duration==0)=[];
end
 %         [state_event state_duration state_end_time] ;
A.state_event=state_event;
A.state_duration=state_duration;
A.state_end_time=state_end_time;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% EYELINK2 SECTION start
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the iti info should be kept in memory for error trials. 
% this way we can go directly to the next iti and skip past all other
% events.
[NEXT_BLACK temp]=sort(find(state_event==S_BLACK));
NEXT_BLACK(abs(temp-(max(temp)+1)))=NEXT_BLACK;
% by setting up the NEXT_ITI array backwards it speeds up erasing procedure.
% if you erase the first position in an array matlab has to rewrite ALL array positions
% by 1. big waist! just erase from the end and matlab dosen't have to
% rewrite anything.

if (EYELINK('initialize') ~= 0)
	clc
	disp(' ');
	disp('   EYELINK(`initialize`) failed!!!' )
	return;
end;
clc;
file_name=input('Input file name:','s');
i = EYELINK('openfile',[file_name,'.edf']);
if i~=0
	disp(['Cannot create EDF file: ' file_name]);
	EYELINK('Shutdown');
	return;
end
disp(' ')
disp(' ')
disp([' the state_duration array has been produced and contains ' num2str(length(state_duration)) ' events.'] )
disp([' the duration of this ' num2str(max_trials) ' trial block will be ' num2str(state_end_time(end)) ' seconds. (' num2str(state_end_time(end)/60) ' mins.)' ] )
cd
pause

EYELINK('command', 'add_file_preamble_text', 'Recorded by BCOE');
%   SET UP TRACKER CONFIGURATION
eyelink('command', 'calibration_type = HV9');
%	set parser (conservative saccade thresholds)
eyelink('command', 'saccade_velocity_threshold = 35');
eyelink('command', 'saccade_acceleration_threshold = 9500');
%	set EDF file contents
% eyelink('command', 'file_event_filter = LEFT,RIGHT,FIXATION,SACCADE,BLINK,MESSAGE');
eyelink('command', 'file_event_filter = LEFT,RIGHT,MESSAGE');
% Sets which types of events will be written to EDF file. See tracker file
% DATA.INI for types.
% Arguments: <list>: list of event types
% LEFT, RIGHT events for one or both eyes
% FIXATION fixation start and end events
% FIXUPDATE fixation (pursuit) state updates
% SACCADE saccade start and end
% BLINK blink start an end
% MESSAGE messages (user notes in file)
% BUTTON button 1..8 press or release
% INPUT changes in input port lines
eyelink('command', 'link_event_filter = LEFT,RIGHT,FIXATION');
% Sets which types of events will be sent through link. See tracker file
% DATA.INI for types.
% Arguments: <list>: list of event types
% LEFT, RIGHT events for one or both eyes
% FIXATION fixation start and end events
% FIXUPDATE fixation (pursuit) state updates
% SACCADE saccade start and end
% BLINK blink start an end
% MESSAGE messages (user notes in file)
% BUTTON button 1..8 press or release

eyelink('command', 'link_sample_data  = LEFT,RIGHT,GAZE,AREA');
% Sets data in samples sent through link. See tracker file DATA.INI for
% types.
% Arguments: <list>: list of data types
% GAZE screen xy (gaze) position
% GAZERES units-per-degree screen resolution
% HREF head-referenced gaze
% PUPIL raw eye camera pupil coordinates
% AREA pupil area
% STATUS warning and error flags
% BUTTON button state and change flags
% INPUT input port data lines

in_tgt=0;
in_fix=0;
out_tgt=0;
t_ITI=0; 
t_error=0;
t_correct=0;
win_lim=5; %radius
el=initeyelinkdefaults;
el.backgroundcolour=c.BACKGROUND(1);
el.targetbeep=1;


[w,screenRect] = SCREEN(0,'OpenWindow',0,[],16);
pause(.01);
SCREEN(w,'fillrect',c.BACKGROUND); 
[buffer,rect]  = SCREEN(0,'OpenOffscreenWindow',0,[],16);
SCREEN(buffer,'fillrect',c.BACKGROUND); 
for i=1:n_loc
    SCREEN(buffer,'filloval',c.WHITE,marker_rect(i,:));  % draw markers
end


SCREEN(w,'TextStyle',1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
[oldFontName,oldFontNumber]=SCREEN(w,'TextFont','Tahoma');
SCREEN(w,'TextSize',40);
ttext='Hit the space bar to continue';
twidth=SCREEN(w,'TextWidth',ttext);
SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y-100,c.BLACK);
keyCode(32)=0;
warning off MATLAB:DeprecatedLogicalAPI
while ~keyCode(32)% SPACE on pcwin
	[keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
end
%warning on %MATLAB:DeprecatedLogicalAPI

SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y-100,c.BACKGROUND);
ttext='Eye tracker set up starting...';
twidth=SCREEN(w,'TextWidth',ttext);
SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y-100,c.BLACK);

err=dotrackersetup(el,el.ENTER_KEY);
el.targetbeep=0;
eye_used = EYELINK('eyeavailable'); % get eye that's tracked
if eye_used == el.BINOCULAR; % if both eyes are tracked
	eye_used = el.LEFT_EYE; % use left eye
end
if eye_used==-1
% 	eye_used=0;
	SCREEN(w,'close');
	SCREEN(buffer,'Close');

	EYELINK('stoprecording');
	EYELINK('closefile');
	EYELINK('shutdown');	
	error('eye_used==-1');
	return	
end

% ttext='Lets Go!!!...';
% twidth=SCREEN(w,'TextWidth',ttext);
% SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y-100,c.BLUE);
% clear ttext twidth;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% EYELINK2 SECTION END
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

SCREEN(w,'TextStyle',1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
[oldFontName,oldFontNumber]=SCREEN(w,'TextFont','Tahoma');
SCREEN(w,'TextSize',80);
ttext='PRO';
twidth=SCREEN(w,'TextWidth',ttext);
SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y-100,c.PRO);
ttext='ANTI';
twidth=SCREEN(w,'TextWidth',ttext);
SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y+100,c.ANTI);
SCREEN(w,'TextSize',40);

screen(w,'waitblanking');
refresh=getsecs;
screen(w,'waitblanking',15);
refresh=(getsecs-refresh)/15;
%SCREEN(w,'Close');
%SCREEN(buffer,'Close');

%max_trials=4 %only for debugging
state_counter=1;
state=1;
tr_num=0;
index=1;
status=state_event(index);

%case S_ITI % ITI
SCREEN(buffer,'FrameOval',c.WHITE,fix_a);
tr_num=tr_num+1;
figure(1)
set(1,'Position', screenRect.*[0 0 1 .96 ])
buttons=0; % prevent from skipping mouse button loop
while buttons(1)==0  
	%wait here for SUBJECT to send mouse click
	setmouse(c_x,c_y);
	[x y buttons]=getmouse;
	warning off MATLAB:DeprecatedLogicalAPI
	[keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
	warning on MATLAB:DeprecatedLogicalAPI
	if keyCode(27)% ESC on pcwin
		SCREEN(w,'Close');
		SCREEN(buffer,'Close');
		close(1);
		return
	end
end
EYELINK('startrecording');
abs_start_time=EYELINK('currenttime');
state_time=state_time*1000+abs_start_time;
HideCursor;
% eye_used = EYELINK('eyeavailable'); % get eye that's tracked
% if eye_used == el.BINOCULAR; % if both eyes are tracked
% 	eye_used = el.LEFT_EYE; % use left eye
% end
% if eye_used==-1
% % 	eye_used=0;
% 	SCREEN(w,'close');
% 	SCREEN(buffer,'Close');
% 
% 	EYELINK('stoprecording');
% 	EYELINK('closefile');
% 	EYELINK('shutdown');	
% 	error('eye_used==-1');
% 	return	
% end
% x=[];
% y=[];
% which_eye=1;erase_eye=0;


while status
	switch status
		case S_ITI % ITI
			SCREEN(buffer,'FrameOval',c.WHITE,fix_a);
			tr_num=tr_num+1;
            
		case S_FIX % fixation
			SCREEN(buffer,'fillarc' ,c.WHITE,fix_a,90,180); % draw fixation 1/3
			SCREEN(buffer,'fillarc' ,c.BLACK ,fix_a,270,180);% draw fixation 2/3
			SCREEN(buffer,'filloval',c.BACKGROUND,fix_b);  % draw fixation 3/3

% 		case S_FIXc % fixation check
		case S_GAP % gap
			SCREEN(buffer,'filloval',c.BACKGROUND,fix_a); % erase fixation			
		case S_CUE_TGT % cue-target
			target=tgt_rect(w_loc(tr_num),:);
			switch A.anti(tr_num)
				case 1, color=c.ANTI;
				case 0, color=c.PRO;
			end
			switch A.peri(tr_num)
				case 0,
					SCREEN(buffer,'filloval',color,fix_a);  % draw cue over fixation
					SCREEN(buffer,'filloval',c.WHITE,target);  % draw target in periphery
				case 1, 
					SCREEN(buffer,'filloval',c.BACKGROUND,fix_a); % erase fixation (repetitive in S_GAP)
					SCREEN(buffer,'filloval',color,target);  % draw cue-target in periphery
			end
            
            % 		case S_CUE_TGTc % cue-target check
        case S_BLACK
            SCREEN(buffer,'FillRect',c.BACKGROUND); % erase entire screen
            for i=1:n_loc
                SCREEN(buffer,'filloval',c.WHITE,marker_rect(i,:));  % draw markers
            end
			NEXT_BLACK(end)=[]; % erase last S_BLACK position as we no longer need it
			
% 		case S_ERROR_1 % didn't fixate
% 			index=NEXT_BLACK(end); % set the state_time index to the next iti skipping past all other events
% 			SCREEN(buffer,'filloval',c.L_GREY); 
% 		case S_ERROR_2 % failed task
% 			index=NEXT_BLACK(end); % set the state_time index to the next iti skipping past all other events
% 			SCREEN(buffer,'filloval',c.L_GREY); 
	end
	screen(w,'waitblanking');
	SCREEN('CopyWindow',buffer,w);
% 	time(tr_num,status)=getsecs;
	time(tr_num,status)=EYELINK('currenttime');
% 	EYELINK('message', '%s' ,t_state(status,:))
	%% it's best to let matlab save the time data as it's much better
	index=index+1;
	status=state_event(index);
% 	while buttons(1)==0 & getsecs < state_time(index)-.011
    current_time=EYELINK('currenttime');
	while buttons(1)==0 & current_time < state_time(index)
% 		if EYELINK('newfloatsampleavailable') > 0
% 			% get the sample in the form of an event structure
% 			evt = EYELINK('newestfloatsample');
% 			x(end+1) = evt.gx(eye_used+1); % +1 as we're accessing MATLAB array
% 			y(end+1) = evt.gy(eye_used+1);
% 			eye_x=(x(end)-(screenRect(3)/2))/pixperdeg;
% 			eye_y=(y(end)-(screenRect(4)/2))/pixperdeg;
% % 			gazeRect=[ x(end)-3 y(end)-3 x(end)+3 y(end)+3];
% % 			gazeRect(gazeRect>864)=864;
% % 			gazeRect(gazeRect<-864)=-864;
% % 			eyerect(which_eye,:)=gazeRect;
% % 			SCREEN(w,'FrameOval',c.GREEN,eyerect(which_eye,:));
% % 	 		which_eye=which_eye+1;
% % 			if which_eye==11, which_eye=1; erase_eye=1;end
% % 			if erase_eye==1 SCREEN(w, 'FrameOval',c.BACKGROUND,eyerect(which_eye,:));end
% 
% 			if abs(eye_x)<win_lim & abs(eye_y)<win_lim
% 				in_fix=1;
% 			else
% 				in_fix=0;
% 			end
% 			tgt=[w_loc(tr_num,:) mod(w_loc(tr_num,:)+((n_loc/2)-1),n_loc)+1];% tgt(1) is the target displayed, tgt(2) is the anti target
% 			in_X=find(abs(loc_XY(tgt,1)-eye_x)<win_lim);
% 			in_Y=find(abs(loc_XY(tgt(in_X),2)-eye_y)<win_lim);
% 			if in_Y
% 				in_tgt=in_X(in_Y);
% 			else
% 				in_tgt=0;
% 			end
% 			if in_tgt > out_tgt % just entered a target
% 				out_tgt=in_tgt;
% 			end
% 			if out_tgt > in_tgt % just leaving a target
% 				out_tgt=0;
% 			end 		
% % 			switch status
% % 				case S_FIXc
% % 					if in_fix==0,
% % 						next_status=S_ERROR_1;
% % 						buttons=1;
% % 					end
% % 				case S_CUE_TGTc
% % 					if in_tgt~=A.anti(tr_num)+1 ,
% % 						next_status=S_ERROR_2;
% % 						buttons=1;
% % 					end
% % 				case S_CUE_TGT
% % 					if in_tgt==abs(A.anti(tr_num)-2), %if in wrong tgt
% % 						next_status=S_ERROR_2;
% % 						buttons=1;
% % 					end
% % 			end % switch status
% 		end % if eyelink sample available
		
		%warning off MATLAB:DeprecatedLogicalAPI
		%[m_x m_y buttons]=getmouse;
		[keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
		if keyCode(27)% ESC on pcwin
			buttons=1; % get out of this loop 
			status=0;% get out of status loop
		end
		%warning on MATLAB:DeprecatedLogicalAPI
	    current_time=EYELINK('currenttime');
	end %buttons(1)==0 & current_time < state_time(index)-.011
	buttons=0; % prevent from skipping mouse button loop
	
% 	if state_event(index-1)==S_FIX & next_status<0% if leaving fix and no error
% 		result=dodriftcorrect_b(el, [], [], 0, 0);
% 		EYELINK('startrecording');
% 	end
	
end % status loop

SCREEN(w,'FillRect',c.BACKGROUND); % erase entire screen
ttext='Done... ';
twidth=SCREEN(w,'TextWidth',ttext);
SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y-100,c.BLUE);
clear ttext twidth;
pause(1)
ShowCursor;
SCREEN(w,'close');
SCREEN(buffer,'Close');

EYELINK('stoprecording');
EYELINK('closefile');
EYELINK('receivefile');
EYELINK('setofflinemode')
%EYELINK('shutdown');	



timea=sort(floor((time(time>=state_time(1))-state_time(1))));
timeb=floor((time-state_time(1)));
timeb(timeb<0)=0;
A.timea=timea;
A.timeb=timeb;
save(file_name, 'A')

state_timea=(state_time-state_time(1));
%time_check=[ num2str([timea state_timea(1:length(timea)) timea-state_timea(1:length(timea)) ]) t_state(state_event(state_event>0),:)]

% clf;
% vline(timeb(:,S_ITI));
% test=max(xlim);
% vline(timeb(:,S_FIX),'k');
% vline(timeb(:,S_CUE_TGT),'b');
% vline(timeb(:,S_GAP),'g');
% xlim([0 test]);
% vline(state_timea,'-.c');
fig(8);clf;
%xlim([-4000 10000]);
hline(.5);
fadething=[c.PRO;c.ANTI]/31;
for tr_num1=1:size(timeb,1)-1%max_trials
	ylim([tr_num1-.5 tr_num1+.5]);
	realign=timeb(tr_num1,S_FIX);
	vline(timeb(tr_num1,S_ITI)-realign,'c');
	vline(max(0,timeb(tr_num1,S_GAP)-realign),'k');
	vline(timeb(tr_num1,S_FIX)-realign,'k');
	vfill(timeb(tr_num1,S_CUE_TGT)-realign,timeb(tr_num1,S_BLACK)-realign,fadething(A.anti(tr_num1)+1,:));	
	vline(timeb(tr_num1+1,S_ITI)-realign,'c');
	xlim([timeb(tr_num1,S_ITI)-realign timeb(tr_num1+1,S_ITI)-realign])
	hline(tr_num1+.5);
end
axis auto ij tight;


c_x-(twidth/2),c_y+100,c.BLUE);
SCREEN(buffer,'TextSize',40);
screen(w,'waitblanking');
SCREEN('CopyWindow',buffer,w);
pause(2)

exit_time01=sort(floor((exit_time(exit_time>=abs_start_time)-abs_start_time)));
time01=sort(floor((time(time>=abs_start_time)-abs_start_time)));
%[[0; state_end_time(1:index-1)-abs_start_time] exit_time01(1:index) time01(1:index) time01(1:index)-[0; state_end_time(1:index-1)-abs_start_time]];


timea=floor((exit_time-abs_start_time));
timea(timea<0)=0;
timeb=floor((time-abs_start_time));
timeb(timeb<0)=0;
e_time=e_time-e_time(1);

% 	[length(timea) length(state_timea(1:length(timea))) length([round(diff(timea)/500/2);dur_iti]) length(t_state(state_event(1:length(timea)),:))]
% 	[num2str([timea state_timea(1:length(timea)) timea-state_timea(1:length(timea)) [round(diff(timea)/100)/10;dur_iti]]) t_state(state_event(1:length(timea)),:)]
A.timea=timea;

A.timeb=timeb;
A.e_x=x;
A.e_y=y;
A.e_time=e_time;


showcursor;
SCREEN('Closeall');
EYELINK('stoprecording');
EYELINK('closefile');
pause(.1)
%[status =] EYELINK('receivefile',['filename'], ['dest'],['dest_is_path'])
EYELINK('receivefile',file_name,[file_name '.edf']);
save(file_name, 'A');
EYELINK('setofflinemode');
EYELINK('shutdown');	
cd
dir([file_name '.*']);

% clf
% vline(timeb(:,S_ITI));
% test=max(xlim);
% vline(timeb(:,S_FIX),'k');
% vline(timeb(:,S_CUE_TGT),'b');
% vline(timeb(:,S_GAP),'g');
% xlim([0 test]);
% vline(state_timea,'-.c');
fig(8);clf;tickout;set(gcf,'Position',[0 3 552 694])
xlim([-dur_iti*1000 (dur_fix+dur_blk )*1000]);
hline(.5);
for tr_num=1:size(A.timeb,1)-1%max_trials
	ylim([tr_num-.5 tr_num+.5]);
	realign=timeb(tr_num,S_FIX);
	vline(timeb(tr_num,S_ITI)-realign,'c');
	if timeb(tr_num,S_GAP)
		vfill(timeb(tr_num,S_FIX)-realign,timeb(tr_num,S_GAP)-realign,c.L_GREY/31);
		vfill(timeb(tr_num,S_GAP)-realign,timeb(tr_num+1,S_ITI)-realign,c.D_GREY/31);
	else
		vfill(timeb(tr_num,S_FIX)-realign,timeb(tr_num,S_CUE_TGT)-realign,c.L_GREY/31);
		vfill(timeb(tr_num,S_CUE_TGT)-realign,timeb(tr_num+1,S_ITI)-realign,c.D_GREY/31);
	end
	
	h=vfill(timeb(tr_num,S_CUE_TGT)-realign,timeb(tr_num,S_BLACK)-realign);
    if A.anti(tr_num)
        set(h,'FaceColor',c.ANTI./31);
        plot(3100,tr_num-(polar2cart(A.ang_ecc(tr_num,:))/25),'w+')
    else
        set(h,'FaceColor',c.PRO./31);
        plot(3100,tr_num+(polar2cart(A.ang_ecc(tr_num,:))/25),'w+')
    end
	%vfill(timeb(tr_num+1,S_ITI)-realign,9000);	
	
	% 	vline(max(0,timeb(tr_num,S_GAP)-realign),'k');
	% 	vline(timeb(tr_num,S_FIX)-realign,'k');
	% 	vline(timeb(tr_num,S_CUE_TGT)-realign,'r');	
    vline(timeb(tr_num+1,S_ITI)-realign,'c');
    eye_range=find(e_time-realign>=timeb(tr_num,S_ITI)-realign & e_time-realign<=timeb(tr_num+1,S_ITI)-realign);
    eye_range(abs(x(eye_range))>3000)=[];
    plot(e_time(eye_range)-realign,tr_num+((x(eye_range)-(screenRect(3)/2))/pixperdeg)/25 ,'g');
    hline(tr_num-.5);
end
drawnow;
axis auto ij tight
ylim([.5 tr_num+.5 ])
set(gca,'YTick', 1:tr_num)
ylabel('Trial Number')
xlabel('Time relative to fixation onset')


